package purchase.wf;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jbpm.JbpmConfiguration;
import org.jbpm.JbpmContext;
import org.jbpm.graph.def.ProcessDefinition;

public class JbpmProcessImageServlet implements Servlet {

	private static Log log = LogFactory.getLog(JbpmProcessImageServlet.class);
	
	public ServletConfig getServletConfig() {
		return this.getServletConfig();
	}

	public String getServletInfo() {
		return this.getServletInfo();
	}

	public void init(ServletConfig servletConfig) throws ServletException {
		log.info("JbpmProcessImageServlet init......");
	}
	
	public void destroy() {
		log.info("JbpmProcessImageServlet destroy......");
	}

	/**
	 * 编码设置
	 * @param request
	 * @param response
	 */
	private void setReqRespEncoding(ServletRequest request,
			ServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
	}

	public void service(ServletRequest request, ServletResponse response)
			throws ServletException, IOException {
		setReqRespEncoding(request, response);

		String processDefinitionId = request.getParameter("processDefinitionId");
		
		JbpmContext jbpmContext = null;
		try {
			jbpmContext = JbpmConfiguration.getInstance().createJbpmContext();
			ProcessDefinition processDefinition = jbpmContext.getGraphSession().getProcessDefinition(
					Long.parseLong(processDefinitionId));
			byte[] bytes = processDefinition.getFileDefinition().getBytes("processimage.jpg");
			
			//write data to page
			OutputStream out = response.getOutputStream();
			out.write(bytes);
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			jbpmContext.close();
		}
	}

}
